import "./index.scss";
import LoginBgImg from "./image/center_card_bg.svg";
import Inbetweening1 from "./image/inbetweening/1.svg";
import Inbetweening2 from "./image/inbetweening/2.svg";
import Inbetweening3 from "./image/inbetweening/3.svg";
import Inbetweening4 from "./image/inbetweening/4.svg";
import QrcodeCornerMark from "./image/form/qrcode_corner_mark.svg";
import RScaleScreen from "r-scale-screen";
import {
  Button,
  Checkbox,
  Form,
  Input,
  Tooltip,
  Modal,
  message,
  notification,
} from "antd";
import {
  LockOutlined,
  UserOutlined,
  SecurityScanOutlined,
  LoginOutlined,
  SmileOutlined,
} from "@ant-design/icons";
import "@/utils/sliderVerification.js";
import { useEffect, useState, useRef } from "react";
import { v4 as uuidv4 } from "uuid";
import { loginApi } from "@/api/user";
import { getGreetingMessageApi } from "@/api/other";
import { useNavigate } from "react-router-dom";
import { observer } from "mobx-react-lite";
import userStore from "@/store/user";
import routerStore from "@/store/router";
import dayjs from "dayjs";
import { updateMenu } from "@/router/menu";

/* 登录页面函数组件 */
const LoginPage = () => {
  // navigate
  const navigate = useNavigate();

  // const [api, contextHolder] = notification.useNotification();

  // 是否显示验证弹窗的标识
  const [isShowVerifyModal, setIsShowVerifyModal] = useState(false);

  // 校验弹出显示类型   1-通过点击按钮   2-点击登录按钮
  const [verifyModalShowType, setVerifyModalShowType] = useState(0);

  // 是否通过验证的标识
  const [isPassVerify, setIsPassVerify] = useState(false);

  // 登录加载标识
  const [isLoginLoading, setIsLoginLoading] = useState(false);

  // 登录表单数据
  const [loginFormData, setLoginFormData] = useState({
    // 用户名
    platFormUserName: "",
    // 密码
    platFormUserPass: "",
  });

  // 登录表单实时数据
  const loginFormDataRef = useRef(loginFormData);

  // 随机时间段温馨提示
  const [greetingMessage, setGreetingMessage] = useState("");

  // Effect
  useEffect(() => {
    loginFormDataRef.current = loginFormData;
  }, [loginFormData]);

  // Effect
  useEffect(() => {
    getGreetingMessageFunc();
  }, []);

  // 获取随机时间段温馨提示的函数
  const getGreetingMessageFunc = async () => {
    await getGreetingMessageApi().then((res) => {
      setGreetingMessage(res.data.data.tip);
    });
  };

  // 时间段计算函数
  const getTimeQuantum = () => {
    const hour = dayjs().hour();
    if (hour >= 6 && hour < 12) {
      return "上午好";
    } else if (hour >= 12 && hour < 18) {
      return "下午好";
    } else if (hour >= 18 && hour < 24) {
      return "晚上好";
    } else {
      return "凌晨好";
    }
  };

  // 登录请求函数
  const login = async (data) => {
    setIsLoginLoading(true);

    await loginApi(loginFormDataRef.current)
      .then((res) => {
        if (res.result == "success") {
          // 设置用户信息
          userStore.setUserInfo(res.data);
          // 设置登录时间
          userStore.setLoginTime(dayjs().valueOf());
          // 设置token
          userStore.setToken(res.data.accessToken);
          // 更新菜单列表
          // updateMenu(res.data.platFormUserLevel);
          // updateMenu("2");
          let authMenuList = updateMenu("1");
          navigate("/layout/home");

          routerStore.setAuthMenuList(authMenuList);
          routerStore.setCurrentRouteKeyPath(["0"]);

          // message.success("登录成功");
          notification.open({
            message: `${
              res.data.platFormUserName
            }，${getTimeQuantum()}，欢迎登录!`,
            description: greetingMessage,
            icon: <SmileOutlined style={{ color: "#1677ff" }} />,
            showProgress: true,
            pauseOnHover: false,
          });
        }
      })
      .finally(() => {
        setIsLoginLoading(false);
      });
  };

  // 初始化滑块验证组件
  const initJigsaw = () => {
    setTimeout(() => {
      jigsaw.init({
        el: document.getElementById("verif_code_box"),
        width: 310, // 可选, 默认310
        height: 155, // 可选, 默认155
        onSuccess: () => {
          // 判断校验弹窗类型
          if (verifyModalShowType == 2) {
            login(loginFormData);
            resetVerifyModalShowType();
          }
          setIsShowVerifyModal(false);
          setIsPassVerify(true);
        },
        onFail: () => {},
        onRefresh: () => {},
      });
    }, 100);
  };

  // 重置校验弹窗类型状态方法
  const resetVerifyModalShowType = () => {
    setVerifyModalShowType(0);
  };

  // 验证点击方法
  const verifyClick = () => {
    setIsShowVerifyModal(true);
    initJigsaw();
    setVerifyModalShowType(1);
  };

  // 验证弹窗关闭点击事件
  const verifyModalCloseClick = () => {
    setIsShowVerifyModal(false);
    resetVerifyModalShowType();
  };

  const onFinish = async (values) => {
    console.log("Success:", values);
    await setLoginFormData(values);
    // 判断是否通过校验
    if (!isPassVerify) {
      setIsShowVerifyModal(true);
      initJigsaw();
      return;
    }

    login(values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <>
      <div className="login_page_wrap">
        <RScaleScreen
          width={1920}
          height={1080}
          boxStyle={{
            backgroundImage: LoginBgImg,
          }}
        >
          {/* 中间卡片 */}
          <div className="center_card_box">
            <div className="left_box">
              {/* 插画 */}
              <img className="inbetweening_1" src={Inbetweening1} />
              <img className="inbetweening_2" src={Inbetweening2} />
              <img className="inbetweening_3" src={Inbetweening3} />
              <img className="inbetweening_4" src={Inbetweening4} />
            </div>
            <div className="right_box">
              {/* 角标 */}
              <Tooltip title="扫描二维码登录" color="#108ee9">
                <img
                  className="qrcode_corner_mark_img"
                  src={QrcodeCornerMark}
                />
              </Tooltip>
              {/* 角标三角形遮罩块 */}
              <div className="qrcode_corner_mark_box"></div>

              {/* 欢迎语 */}
              <span className="welcome_speech_text">恒蓝云后台管理系统</span>

              {/* 登录表单模块 */}
              <div className="login_form_box">
                <Form
                  name="basic"
                  labelCol={{
                    span: 0,
                  }}
                  wrapperCol={{
                    span: 24,
                  }}
                  style={{
                    maxWidth: 600,
                  }}
                  initialValues={{
                    remember: true,
                  }}
                  size="large"
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                >
                  <Form.Item
                    label=""
                    name="platFormUserName"
                    className="user_name_form_item"
                    rules={[
                      {
                        required: true,
                        message: "请输入用户名!",
                      },
                    ]}
                  >
                    <Input
                      prefix={<UserOutlined className="fx_icon" />}
                      placeholder="请输入用户名"
                    ></Input>
                  </Form.Item>

                  <Form.Item
                    label=""
                    name="platFormUserPass"
                    className="password_form_item"
                    rules={[
                      {
                        required: true,
                        message: "请输入密码!",
                      },
                    ]}
                  >
                    {/* <LockOutlined  /> */}
                    <Input.Password
                      prefix={<LockOutlined className="fx_icon" />}
                      placeholder="请输入密码"
                    ></Input.Password>
                  </Form.Item>

                  {/* 验证按钮 */}
                  {isPassVerify ? (
                    <Button
                      className="tg_vf_btn"
                      color="default"
                      icon={
                        <SecurityScanOutlined
                          style={{
                            fontSize: 20,
                            color: "#ffffff",
                          }}
                        />
                      }
                    >
                      <span className="click_vf_btn_text">通过验证</span>
                    </Button>
                  ) : (
                    <Button
                      className="click_vf_btn"
                      color="primary"
                      variant="outlined"
                      onClick={verifyClick}
                      icon={
                        <SecurityScanOutlined
                          style={{
                            fontSize: 20,
                          }}
                        />
                      }
                    >
                      <span className="click_vf_btn_text">点击验证</span>
                    </Button>
                  )}

                  <Form.Item label={null}>
                    <Button
                      className="login_btn"
                      type="primary"
                      htmlType="submit"
                      variant="outlined"
                      loading={isLoginLoading}
                      onClick={() => {
                        setVerifyModalShowType(2);
                      }}
                      icon={
                        <LoginOutlined
                          style={{
                            marginRight: 10,
                            // marginTop: 0.6,
                          }}
                        />
                      }
                    >
                      登录
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
          </div>
        </RScaleScreen>

        {/* 滑块验证码组件弹窗 */}
        <Modal
          open={isShowVerifyModal}
          title="按住滑块进行验证"
          onCancel={verifyModalCloseClick}
          footer={null}
          className="slider_verif_code_modal"
          destroyOnClose={true}
        >
          {isShowVerifyModal ? <div id="verif_code_box"></div> : null}
        </Modal>
      </div>
    </>
  );
};

export default observer(LoginPage);
